<template>
  <!--  工艺路线-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="工艺路线名称">
          <el-input v-model="searchParam.name" placeholder="请输入工艺路线名称" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button type="primary" :icon="Plus" @click="handleAdd()">新建</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 350px)">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            <!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{
              (pageSearch.current - 1) * pageSearch.pageSize
              + scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="工艺路线名称" align="center" min-width="300"/>
        <el-table-column prop="code" label="工艺路线编码" align="center" min-width="200"/>
        <!--				<el-table-column prop="traceabilityCode" label="追溯码编号" align="center" min-width="200" />-->
        <!--				<el-table-column prop="processRouteStatus" label="工艺路线状态" align="center" min-width="200">-->
        <!--					<template #default="scope"> {{ scope.row.processRouteStatus == 1 ? '合格工艺路线' : '特采工艺路线' }} </template>-->
        <!--				</el-table-column>-->
        <!--				<el-table-column prop="contacts" label="联系人" align="center" min-width="200" />-->
        <!--				<el-table-column prop="contactsPhone" label="联系电话" align="center" min-width="200" />-->
        <!--				<el-table-column prop="address" label="地址" align="center" min-width="200" show-overflow-tooltip />-->
        <!--				<el-table-column prop="description" label="备注" align="center" min-width="200" show-overflow-tooltip />-->
        <el-table-column label="操作" align="center" fixed="right" width="240">
          <template #default="scope">
            <el-button @click="handConfig(scope.row)" size="small" plain type="text"
                       :icon="Edit">配置
            </el-button>
            <el-button @click="handleEdit(scope.row)" type="text" size="small" plain
                       :icon="Edit">编辑
            </el-button>
            <el-button @click="handleDel(scope.row)" text type="danger" size="small"
                       :icon="Delete">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current"
                       v-model:page-size="pageSearch.pageSize" :page-sizes="[10, 20, 50, 100, 200, 500]"
                       layout="total, sizes, prev, pager, next" :total="pageTotal" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!-- 弹窗表单 -->
    <el-dialog v-model="showCrud" :title="crudTitle" width="900px">
      <el-form :model="formData" label-width="120px" ref="ruleFormRef" :rules="rules" class="demo-ruleForm">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item required label="工艺路线名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入工艺路线名称" clearable
                        style="width:300px "></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item required label="工艺路线编码" prop="code">
              <el-input v-model="formData.code" placeholder="请输入工艺路线编码" clearable
                        style="width:300px "></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="showConfigCrud" :title="crudTitle" width="900px">
      <div class="drag-container">
        <div class="device-list">
          <h3 style="margin-bottom: 10px">可用设备</h3>
          <el-input
              v-model="deviceSearchParam.name"
              placeholder="输入设备名称搜索"
              clearable
              @input="searchDevices"
              style="margin-bottom: 10px"
          />
          <div class="device-list-content">
            <div
                v-for="device in availableDevices"
                :key="device.id"
                class="device-item"
                :class="{ 'selected-item': isSelected(device) }"
                draggable="true"
                @dragstart="handleDragStart($event, device)"
                @click="addToSelected(device)"
            >
              {{ device.name }}
              <span v-if="isSelected(device)" class="selected-tag">✓</span>
            </div>
          </div>
          <div style="width: 100%;display: flex;justify-content: flex-end">
            <el-pagination
                small
                layout="prev, pager, next"
                :total="deviceTotal"
                :page-size="deviceSearchParam.pageSize"
                :current-page="deviceSearchParam.current"
                @current-change="handleDevicePageChange"
            />
          </div>
        </div>

        <!-- 右侧已选设备列表（保持拖拽排序功能） -->
        <div class="selected-list">
          <h3 style="margin-bottom: 10px">已选设备</h3>
          <transition-group name="list" tag="div">
            <div
                v-for="(device, index) in selectedDevices"
                :key="device.id"
                class="selected-item"
                draggable="true"
                @dragstart="handleDragStart($event, device, index)"
                @dragover.prevent="handleDragOver($event, index)"
                @dragenter="handleDragEnter($event, index)"
                @drop="handleDrop($event, index)"
            >
              {{ device.name }}
              <span class="remove-btn" @click="removeDevice(index)">×</span>
            </div>
          </transition-group>
        </div>
      </div>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showConfigCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSaveConfig">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {ref, reactive, computed, watch} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {useEquipmentData} from '@/hooks/baseData/equipment';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Search, Share, Upload, Refresh, Plus, DocumentCopy} from '@element-plus/icons-vue';


const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const configTableShow = ref(false);

const handleClick = (e) => {
  console.log(e, 'handleClick');
};

const rowInfo = ref({});


const workOrderList = ref({});

const showMaterial = ref(false);

const showConfigCrud = ref(false)

const workOrderChange = (e) => {
  if (!e) {
    formData.count = null;
    return false;
  }
  axiosInstance.post('/api/workOrder/queryByWorkId', {id: e})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        formData.count = res.data.orderCount;
        formData.materialId = res.data.materialId;
        formData.productId = res.data.productId;
      });
};


// 通用更新接口函数
const handleUpdateQualityScheme = (updatedRowInfo) => {
  axiosInstance.put('/api/basedataQualityScheme/update', updatedRowInfo).then(res => {
    if (res.code != 200) {
      ElMessage.error(res.message);
      return false;
    }
    ElMessage.success('操作成功!');
    showConfig.value = false;
    showMaterial.value = false;
    // 刷新配置质检项列表
    getList();
  });
};


const pageTotal = ref(null);//页面总数
// const formData = reactive({});//form表单
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const searchParam = ref({});//页面检索条件
const showConfig = ref(false);
const configData = ref({});
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});//弹出层标题
import type {ComponentSize, FormInstance, FormRules} from 'element-plus';

const ruleFormRef = ref<FormInstance>();

interface RuleForm {
  name: string;
  code: string;
}


const originalFormData = reactive<RuleForm>({
  name: '',
  code: ''
});

let formData = reactive<RuleForm>(originalFormData);


const rules = reactive<FormRules<formData>>({
  name: [
    {required: true, message: '请输入工艺路线名称', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '请输入工艺路线编码', trigger: 'blur'}
  ],
  traceabilityCode: [
    {required: true, message: '请输入追溯码编号', trigger: 'blur'}
  ],
  processRouteStatus: [
    {required: true, message: '请选择工艺路线状态', trigger: 'blur'}
  ],
  contacts: [
    {required: true, message: '请输入联系人', trigger: 'blur'}
  ],
  contactsPhone: [
    {required: true, message: '请输入联系电话', trigger: 'blur'}
  ],
  address: [
    {required: true, message: '请输入地址', trigger: 'blur'}
  ]
});


// const paginatedData = reactive([])//列表数据
const paginatedData = ref<RuleForm[]>([]);

const materiaList = ref([]);//物料表
const userList = ref([]);//人员
const workRoomList = ref([]);//车间
const procedureOrderList = ref([]);//工序订单

const getOption = () => {
  axiosInstance.post('/api/basedataUser/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        userList.value = res.data;
      });

  axiosInstance.post('/api/basedataOrganization/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        workRoomList.value = res.data;
      });
};


// 获取列表接口
const getList = () => {
  axiosInstance.post('/api/basedata/processRoute/getPage', {
    ...searchParam.value,
    ...pageSearch.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
      });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1;
  // current.value = 1
  getList();
};

// 点击新建
const handleAdd = () => {
  isEdit.value = false;
  // ruleFormRef.value.resetFields()
  formData = reactive({});
  showCrud.value = true;
};

const dragItem = ref(null);
const dragIndex = ref(null);


const selectedDevices = reactive([]);

const deviceSearchParam = reactive({
  current: 1,
  pageSize: 10,
  name: ''
});

const deviceTotal = ref(0);
const availableDevices = ref<any[]>([]); // 替换原有的静态数据

// 获取设备列表
const fetchAvailableDevices = async () => {
  try {
    const res = await axiosInstance.post('/api/basedata/equipmentResource/getPage', deviceSearchParam);
    if (res.code === 200) {
      availableDevices.value = res.data.records;
      deviceTotal.value = res.data.total;
    }
  } catch (error) {
    ElMessage.error('获取设备列表失败');
  }
};

// 设备搜索
const searchDevices = () => {
  deviceSearchParam.current = 1; // 搜索时重置到第一页
  fetchAvailableDevices();
};

// 分页变化
const handleDevicePageChange = (current: number) => {
  deviceSearchParam.current = current;
  fetchAvailableDevices();
};


// // 计算属性：过滤后的设备列表（前端过滤，可选）
// const filteredAvailableDevices = computed(() => {
//   if (!deviceSearchParam.name) return availableDevices.value;
//   return availableDevices.value.filter(device =>
//       device.name.includes(deviceSearchParam.name)
//   );
// });

// 拖拽开始
const handleDragStart = (event, item, index) => {
  dragItem.value = item;
  dragIndex.value = index;
  event.dataTransfer.effectAllowed = 'move';
  event.dataTransfer.setData('text/plain', JSON.stringify(item));
};

// 拖拽经过
const handleDragOver = (event, index) => {
  event.preventDefault();
  event.dataTransfer.dropEffect = 'move';
};

// 拖拽进入
const handleDragEnter = (event, index) => {
  event.preventDefault();
  if (dragIndex.value !== null && dragIndex.value !== index) {
    const dragItem = selectedDevices[dragIndex.value];
    selectedDevices.splice(dragIndex.value, 1);
    selectedDevices.splice(index, 0, dragItem);
    dragIndex.value = index;
  }
};

// 判断设备是否已选中
const isSelected = (device: any) => {
  return selectedDevices.some(item => item.id === device.id);
};

// 点击添加到右侧列表（优化后）
const addToSelected = (device: any) => {
  if (!isSelected(device)) {
    selectedDevices.push({...device});
  } else {
    ElMessage.warning('该设备已添加');
  }
};

// 拖拽放置
const handleDrop = (event, index) => {
  event.preventDefault();

  // 如果是从左侧拖过来的新设备
  if (dragIndex.value === null) {
    const data = JSON.parse(event.dataTransfer.getData('text/plain'));
    if (!selectedDevices.some(item => item.id === data.id)) {
      selectedDevices.splice(index, 0, data);
    }
  }

  dragItem.value = null;
  dragIndex.value = null;
};

// 移除设备
const removeDevice = (index) => {
  selectedDevices.splice(index, 1);
};

// 保存配置
const handleSaveConfig = () => {
  console.log('保存的设备数组:', selectedDevices);
  // 这里可以添加保存到后端的逻辑

  formData.processRoute = JSON.stringify(selectedDevices)
  axiosInstance.put('/api/basedata/processRoute/update', formData).then(res => {
    ElMessage.success('操作成功!');
    showConfigCrud.value = false;
    getList(); // 刷新数据
  });
};


// 编辑
const handleEdit = (row: any) => {
  isEdit.value = true;
  Object.assign(formData, row);
  showCrud.value = true;
};

const handConfig = (row: any) => {
  const info = {...row};

  // 安全清空数组（保持响应性）
  selectedDevices.splice(0, selectedDevices.length);

  // 处理processRoute数据
  if(info.processRoute) {
    try {
      const parsed = JSON.parse(info.processRoute);
      // 确保解析结果是数组
      if(Array.isArray(parsed)) {
        parsed.forEach(item => selectedDevices.push(item));
      }
    } catch(e) {
      console.error("解析processRoute失败:", e);
    }
  }

  Object.assign(formData, info);
  showConfigCrud.value = true;
}

// 删除记录
const handleDel = (row: any) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.delete(`/api/basedata/processRoute/delete`, {
      data: {
        ids: [row.id]
      }
    }).then(res => {
      ElMessage.success('删除成功');
      getList(); // 刷新数据
    });


  });
};


const processRouteJSON = ref(null)


// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
  if (!e) return;
  await e.validate((valid, fields) => {
    if (valid) {
      if (isEdit.value) {
        // 编辑
        axiosInstance.put('/api/basedata/processRoute/update', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      } else {
        // formData.teamUserDTOS = {
        // 	userId: formData.teamUser
        // };
        axiosInstance.post('/api/basedata/processRoute/save', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      }

    }
  });
};


onMounted(() => {
  getList();
  fetchAvailableDevices()
  // getOption();
});

</script>
<style scoped>
.drag-container {
  display: flex;
  gap: 20px;
  height: 500px;
}

.device-list, .selected-list {
  flex: 1;
  border: 1px solid #ddd;
  padding: 10px;
  overflow-y: auto;
}

.device-item, .selected-item {
  padding: 10px;
  margin-bottom: 8px;
  background: #f5f5f5;
  cursor: move;
  position: relative;
}

.selected-item {
  background: #e6f7ff;
}

.remove-btn {
  position: absolute;
  right: 10px;
  cursor: pointer;
  color: red;
}

.list-move {
  transition: transform 0.3s ease;
}

.device-list-content {
  height: calc(100% - 100px);
  overflow-y: auto;
}

.pagination-wrapper {
  position: absolute;
  bottom: 10px;
  left: 10px;
  right: 10px;
  margin-left: auto;
}

.device-item {
  position: relative;
  transition: all 0.3s;
}

.device-item:hover {
  background: #e1f5fe;
  cursor: default;

}

.device-item:not(.selected-item):hover {
  cursor: pointer;

}

.selected-item {
  background: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.selected-tag {
  position: absolute;
  right: 10px;
  color: #1890ff;
  font-weight: bold;
}

</style>
